import * as jsPDF from "jspdf";
import * as svg2pdf from "svg2pdf.js";
import { OpenSheetMusicDisplay,BackendType } from "opensheetmusicdisplay";

async function downloadPDF(osmdInstance, pdfName) {
  if (osmdInstance.backendType !== BackendType.SVG) {
    console.log(
      "[OSMD] createPdf(): Warning: createPDF is only supported for SVG background for now, not for Canvas." +
        " Please use osmd.setOptions({backendType: SVG})."
    );
    return;
  }

  if (pdfName === undefined) {
    pdfName = osmdInstance.sheet.FullNameString + ".pdf";
  }

  const backends = osmdInstance.drawer.Backends;
  let svgElement = backends[0].getSvgElement();

  let pageWidth = 210;
  let pageHeight = 297;
  const engravingRulesPageFormat = osmdInstance.rules.PageFormat;
  if (engravingRulesPageFormat && !engravingRulesPageFormat.IsUndefined) {
    pageWidth = engravingRulesPageFormat.width;
    pageHeight = engravingRulesPageFormat.height;
  } else {
    pageHeight =
      (pageWidth * svgElement.clientHeight) / svgElement.clientWidth;
  }
  const orientation = pageHeight > pageWidth ? "p" : "l";
  const pdf = new jsPDF.jsPDF({
    orientation: orientation,
    unit: "mm",
    format: [pageWidth, pageHeight],
  });
  //const scale = pageWidth / svgElement.clientWidth;
  for (let idx = 0, len = backends.length; idx < len; ++idx) {
    if (idx > 0) {
      pdf.addPage();
    }
    svgElement = backends[idx].getSvgElement();

    if (!pdf.svg && !svg2pdf) {
      // this line also serves to make the svg2pdf not unused, though it's still necessary
      // we need svg2pdf to have pdf.svg defined
      console.log("svg2pdf missing, necessary for jspdf.svg().");
      return;
    }
    await pdf.svg(svgElement, {
      x: 0,
      y: 0,
      width: pageWidth,
      height: pageHeight,
    });
  }

  pdf.save(pdfName); // save/download the created pdf
  //pdf.output("pdfobjectnewwindow", {filename: "osmd_createPDF.pdf"}); // open PDF in new tab/window

  // note that using jspdf with svg2pdf creates unnecessary console warnings "AcroForm-Classes are not populated into global-namespace..."
  // this will hopefully be fixed with a new jspdf release, see https://github.com/yWorks/jsPDF/pull/32
}

/**
 * 
 * @param {String} url mxl文件的url
 * @param {String} pdfName 下载的pdf文件的名称
 */
export default async function osmdToDownLoad(url,pdfName) {
  const div = document.createElement("div");
  div.style.visibility='hidden';
  document.body.appendChild(div);
  const xmlShowEl = div;
 const  osmdInstance = new OpenSheetMusicDisplay(xmlShowEl);

  await osmdInstance.load(url);
  osmdInstance.autoResizeEnabled = true;
  osmdInstance.resizeHandlerAttached = true;

  await osmdInstance.render(); // 先渲染出来

  await downloadPDF(osmdInstance,pdfName); // 下载
  div.remove(); // 删除渲染的东西
}
